package com.level.restful.util;

import com.alibaba.fastjson.JSONObject;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author
 * xml转json
 */
public class XmlToJsonUtil {
    /**
     * 转换一个xml格式的字符串到json格式
     *
     * @param xml
     *            xml格式的字符串
     * @return 成功返回json 格式的字符串;失败反回null
     */
    public static  JSONObject xmlToJSON(String xml) throws Exception{
        JSONObject obj = new JSONObject();
//        try {
            InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
            SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(is);
            Element root = doc.getRootElement();
            obj.put(root.getName(), iterateElement(root));
            return obj;
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            return null;
//        }
    }

    /**
     * 转换一个xml格式的字符串到json格式
     *
     * @param file
     *            java.io.File实例是一个有效的xml文件
     * @return 成功反回json 格式的字符串;失败反回null
     */
    public static String xmlToJSON(File file) {
        JSONObject obj = new JSONObject();
        try {
            SAXBuilder sb = new SAXBuilder();
            Document doc = sb.build(file);
            Element root = doc.getRootElement();
            obj.put(root.getName(), iterateElement(root));
            return obj.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 一个迭代方法
     *
     * @param element
     *            : org.jdom.Element
     * @return java.util.Map 实例
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static Map iterateElement(Element element) {
        List jiedian = element.getChildren();
        Element et = null;
        Map obj = new HashMap();
        List list = null;
        for (int i = 0; i < jiedian.size(); i++) {
            list = new LinkedList();
            et = (Element) jiedian.get(i);
            if ("".equals(et.getTextTrim())) {
                if (et.getChildren().size() == 0) {
                    continue;
                }
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }


//    public static void main(String[] args) throws Exception{
//
////       String s =  PropertiesUtil.getkey("msg_deom_id", "application-dev.properties");
//        String xml  = "<Response><ResponseCode>0</ResponseCode><ResponseMsg></ResponseMsg><HosTranSerNo>163</HosTranSerNo><RegDate>2019-07-07</RegDate><DeptID>202</DeptID><DeptName>内科</DeptName><DoctID>111</DoctID><DoctName>陈玉秋</DoctName><TimeRegion>08:00</TimeRegion><RegID>1</RegID><ReserveKey>163</ReserveKey><RegFee>14.00</RegFee><TimeRemarks></TimeRemarks></Response>";
//        JSONObject json =  XmlToJsonUtil.xmlToJSON(xml);
//        System.out.println(json.getJSONObject("Response").getString("DoctName"));
//        System.out.println(json.getJSONObject("Response").getJSONArray("DoctNam").get(0));
//    }

    public static void main(String [] str) throws Exception {
        String xml = "<XmlTcp><code>0</code><return name=\"READCARDREADMAGCARDNO\"><arguments><string id=\"ERROR\">SUCCESS</string><string id=\"CARDNO\">174399</string></arguments></return></XmlTcp>";
        JSONObject json = xmlToJSON(xml);
        System.out.println(json);

    }
}